<template>
  <div class="banner-manage">
    <!-- 轮播图查询表单 -->
    <el-form :inline="true" :model="searchForm" class="banner-search" ref="searchFormRef">
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择" clearable>
          <el-option label="全部" value="" />
          <el-option label="启用" value="0" />  <!-- 状态值改为0 -->
          <el-option label="封禁" value="1" />  <!-- 状态值改为1 -->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="fetchBanners">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-button
        type="primary"
        icon="Plus"
        @click="openAddDialog"
        style="margin-bottom: 10px;"
    >
      新增轮播图
    </el-button>
    <el-button
        type="danger"
        icon="Delete"
        @click="batchDelete"
        style="margin-bottom: 10px; margin-left: 10px;"
        :disabled="selectedIds.length === 0"
    >
      批量删除
    </el-button>

    <!-- 轮播图列表 -->
    <el-card
        v-for="banner in bannerList"
        :key="banner.id"
        class="banner-card"
        :data-id="banner.id"
    >
      <div class="banner-info">
        <el-checkbox
            v-model="selectedIds"
            :label="banner.id"
            style="margin-right: 10px;"
        ></el-checkbox>
        <img :src="banner.bannerUrl" class="banner-image" :alt="banner.title || '轮播图'" />
        <div class="banner-meta">
          <p>轮播图编号：{{ banner.id }}</p>
          <p>
            状态：
            <el-switch
                v-model="banner.status"
                @change="handleStatusChange(banner)"
                @click.prevent
                :active-value="0"
            :inactive-value="1"
            :disabled="statusUpdating.has(banner.id)"
            />
          </p>
        </div>
      </div>
      <div class="banner-actions">
        <el-button type="text" icon="Edit" @click="openEditDialog(banner)">编辑</el-button>
        <el-button type="text" icon="Delete" @click="deleteBanner(banner.id)">删除</el-button>
      </div>
    </el-card>

    <!-- 空状态 -->
    <div v-if="bannerList.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无轮播图数据" />
      <el-button
          type="primary"
          icon="Plus"
          @click="openAddDialog"
          style="margin-top: 15px;"
      >
        立即新增
      </el-button>
    </div>
    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px;"
    />

    <!-- 新增/编辑轮播图弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form
          :model="form"
          label-width="120px"
          :rules="formRules"
          ref="formRef"
      >
        <el-form-item label="轮播图" prop="image">
          <el-upload
              action="#"
              :http-request="handleImageUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :file-list="imageFileList"
              accept="image/*"
              :limit="1"
              :on-exceed="handleExceed"
              list-type="picture"
          >
            <el-button icon="Picture">上传轮播图</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 JPG、PNG 等图片格式，大小不超过 5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="form.status"
              :active-value="0"
          :inactive-value="1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBanner">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading, ElEmpty } from 'element-plus'
import http from '@/request/http'


export default {
  components: { ElEmpty },
  setup() {
    const statusUpdating = ref(new Set()); // 存储正在更新的banner.id
    // 1. 查询与列表相关状态
    const searchForm = reactive({})
    const bannerList = ref([])  // 轮播图列表数据
    const currentPage = ref(1)  // 分页组件当前页
    const pageSize = ref(5)     // 分页组件每页条数
    const total = ref(0)        // 总数据条数（匹配后端data.total）
    const loading = ref(false)  // 加载状态标识
    const selectedIds = ref([]) // 选中的轮播图ID（批量删除用）
    const searchFormRef = ref(null) // 查询表单引用

    // 2. 弹窗相关状态
    const dialogVisible = ref(false) // 弹窗显示/隐藏
    const isAdd = ref(true)          // true=新增，false=编辑
    const dialogTitle = ref("新增轮播图") // 弹窗标题
    const form = reactive({
      id: null,
      url: '',       // 图片URL（回显用）
      status: 0,     // 默认状态改为启用（0）
      image: null    // 上传的图片文件（提交用）
    })
    const imageFileList = ref([]) // 上传组件文件列表（预览用）
    const formRef = ref(null)     // 弹窗表单引用

    // 3. 表单验证规则
    const formRules = reactive({
      image: [
        { required: isAdd.value,
          message: '请上传轮播图',
          trigger: 'submit' }
      ]
    })

    // 监听isAdd变化，动态更新表单验证规则
    watch(isAdd, (newVal) => {
      formRules.image[0].required = newVal;
    })


    // 5. 获取轮播图列表（核心修改：状态映射反转）
    const fetchBanners = async () => {
      try {
        loading.value = true;
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          // 状态映射改为：0→启用（ENABLE），1→封禁（DISABLE）
          bannerStatus: searchForm.status === '' || searchForm.status === undefined
              ? undefined
              : searchForm.status === 0  // 0表示启用
                  ? 'ENABLE'
                  : 'DISABLE'  // 1表示封禁
        };

        const res = await http.post('/api/banner/getBanner',params)

        // 后端状态转换为前端状态：ENABLE→0（启用），DISABLE→1（封禁）
        bannerList.value = (res.data.items || []).map(banner => ({
          ...banner,
          status: banner.bannerStatus === 'ENABLE' ? 0 : 1
        }));
        total.value = res.data.total || 0;
      } catch (error) {
        bannerList.value = [];
      } finally {
        loading.value = false;
      }
    };

    // 6. 重置查询条件
    const resetSearch = () => {
      searchForm.status = '';
      currentPage.value = 1;
      pageSize.value = 5;
      selectedIds.value = [];
      fetchBanners();
    }

    // 7. 分页事件处理
    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentPage.value = 1;
      fetchBanners();
    };
    const handleCurrentPageChange = (val) => {
      currentPage.value = val;
      fetchBanners();
    };

    // 8. 弹窗操作（新增/编辑）
    const openAddDialog = () => {
      isAdd.value = true;
      dialogTitle.value = '新增轮播图';
      form.id = null;
      form.url = '';
      form.status = 0;  // 新增默认启用（0）
      form.image = null;
      imageFileList.value = [];
      dialogVisible.value = true;
    };
    const openEditDialog = (row) => {
      isAdd.value = false;
      dialogTitle.value = '编辑轮播图';
      form.id = row.id;
      form.url = row.bannerUrl;
      form.status = row.status;  // 使用反转后的状态值
      form.image = null;
      imageFileList.value = row.bannerUrl ? [{
        url: row.bannerUrl,
        name: `轮播图${row.id}`
      }] : [];
      dialogVisible.value = true;
    };

    // 9. 图片上传处理
    const handleImageUpload = async (options) => {
      const file = options.file;
      if (!file.type.startsWith('image/')) {
        ElMessage.error('请上传JPG/PNG等图片格式');
        options.onError();
        return;
      }
      if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过5MB');
        options.onError();
        return;
      }
      form.image = file;
      options.onSuccess({status: 'success'});
    };
    const handleUploadSuccess = () => ElMessage.success('图片预览成功');
    const handleUploadError = () => ElMessage.error('图片预览失败');
    const handleExceed = () => ElMessage.warning('最多只能上传1张图片');

    // 10. 保存轮播图（新增/编辑）
    const saveBanner = async () => {
      const valid = await formRef.value.validate().catch(() => false);
      if (!valid) return;

      try {
        const formData = new FormData();
        if (form.image) formData.append('banner', form.image);
        formData.append('bannerStatus', form.status);  // 直接传递0/1

        if (isAdd.value) {
          await http.post('/api/banner/addBanner', formData)
          ElMessage.success('新增轮播图成功');
        } else {
          if (!form.image){
            ElMessage.error('请上传图片');
            return;
          }else {
            await http.post(`/api/banner/updateBanner/${form.id}`, formData,)
            ElMessage.success('编辑轮播图成功');
          }

        }

        dialogVisible.value = false;
        fetchBanners(); // 保存后刷新列表

      } catch (error) {
        console.error('保存轮播图异常：', error);
        ElMessage.error('保存失败，请检查参数或网络');
      }
    };

    // 11. 状态切换（核心修改：状态含义反转）
    const handleStatusChange = async (banner) => {
      let loadingInstance;
      const targetStatus = banner.status;
      // 状态反转逻辑：0→1，1→0
      const originalStatus = targetStatus === 0 ? 1 : 0;

      // 防止重复提交
      if (statusUpdating.value.has(banner.id)) return;
      statusUpdating.value.add(banner.id);

      try {
        // 参数验证
        if (![0, 1].includes(targetStatus)) {
          ElMessage.error('状态值无效，请重试');
          banner.status = originalStatus;
          return;
        }

        loadingInstance = ElLoading.service({
          target: `.banner-card[data-id="${banner.id}"]`,
          text: '更新中...'
        });

        // 调用状态更新API，传递0/1状态值
        await http.post(
            `/api/banner/updateStatus/${banner.id}?status=${targetStatus}`)
        // 刷新列表数据
        await fetchBanners();

        // 提示信息根据新状态调整
        ElMessage.success(targetStatus === 0 ? '已启用轮播图' : '已封禁轮播图');

      } catch (error) {
        // 出错时回滚状态
        banner.status = originalStatus;
        ElMessage.error(`状态更新失败: ${error.message}`);
        console.error('状态更新异常详情:', error);
      } finally {
        statusUpdating.value.delete(banner.id);
        if (loadingInstance) loadingInstance.close();
      }
    };

    // 12. 单条删除
    const deleteBanner = async (id) => {
      try {
        const confirmResult = await ElMessageBox.confirm(
            '确定删除该轮播图？删除后不可恢复',
            '删除确认',
            { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }
        );

        if (confirmResult === 'confirm') {
          await http.delete(`/api/banner/deleteBanner/${id}`)
          ElMessage.success('删除成功');
          fetchBanners();
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除轮播图异常:', error);
        }
      }
    };

    // 13. 批量删除
    const batchDelete = async () => {
      if (selectedIds.value.length === 0) {
        ElMessage.warning('请选择要删除的轮播图');
        return;
      }

      try {
        const confirmResult = await ElMessageBox.confirm(
            `确定要删除选中的${selectedIds.value.length}个轮播图吗？`,
            '批量删除确认',
            { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
        );

        if (confirmResult === 'confirm') {
          await http.delete('/api/banner/deleteBannerList',selectedIds.value)

          ElMessage.success('批量删除成功');
          selectedIds.value = [];
          fetchBanners();
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除轮播图异常:', error);
        }
      }
    };

    // 初始化加载
    onMounted(() => fetchBanners());

    return {
      searchForm,
      bannerList,
      currentPage,
      pageSize,
      total,
      loading,
      selectedIds,
      dialogVisible,
      isAdd,
      dialogTitle,
      form,
      imageFileList,
      formRef,
      formRules,
      searchFormRef,
      statusUpdating,
      fetchBanners,
      resetSearch,
      handleSizeChange,
      handleCurrentPageChange,
      openAddDialog,
      openEditDialog,
      handleImageUpload,
      handleUploadSuccess,
      handleUploadError,
      handleExceed,
      saveBanner,
      handleStatusChange,
      deleteBanner,
      batchDelete
    };
  }
};
</script>

<style scoped>
.banner-manage {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.banner-search {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.banner-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.banner-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.banner-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.banner-image {
  width: 400px;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

.banner-meta {
  margin-left: 20px;
  line-height: 1.8;
}

.banner-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
}

.loading-state {
  padding: 50px 0;
  text-align: center;
}
</style>
